<template>
  <div style="height: calc(100% - 46px)">
    <a-spin :spinning="loading">
      <template v-if="treeData.length > 0">
        <BasicTree
          ref="basicTree"
          class="depart-rule-tree"
          checkable
          :treeData
          :checkedKeys
          :selectedKeys
          :expandedKeys
          check-strictly
          style="height: 100%; overflow: auto"
          @check="onCheck"
          @expand="onExpand"
          @select="onSelect"
        >
          <template #title="{ slotTitle, ruleFlag }">
            <span>{{ slotTitle }}</span>
            <Icon v-if="ruleFlag" icon="ant-design:align-left-outlined" style="margin-left: 5px; color: red" />
          </template>
        </BasicTree>
      </template>
      <a-empty v-else description="无可配置部门权限" />

      <div :class="[`${prefixCls}`]" style="justify-content: space-between">
        <a-dropdown :trigger="['click']" placement="top">
          <template #overlay>
            <a-menu>
              <a-menu-item key="3" @click="toggleCheckALL(true)">选择全部</a-menu-item>
              <a-menu-item key="4" @click="toggleCheckALL(false)">取消选择</a-menu-item>
              <a-menu-item key="5" @click="toggleExpandAll(true)">展开全部</a-menu-item>
              <a-menu-item key="6" @click="toggleExpandAll(false)">折叠全部</a-menu-item>
              <a-menu-item key="7" @click="toggleRelationAll(false)">层级关联</a-menu-item>
              <a-menu-item key="8" @click="toggleRelationAll(true)">层级独立</a-menu-item>
            </a-menu>
          </template>
          <a-button preIcon="ant-design:up-outlined">树操作</a-button>
        </a-dropdown>
        <a-button type="primary" preIcon="ant-design:save-filled" @click="onSubmit">保存</a-button>
      </div>
    </a-spin>
    <DepartDataRuleDrawer @register="registerDataRuleDrawer" />
  </div>
</template>

<script lang="ts" setup>
  import { watch, computed, ref } from 'vue';
  import { useDrawer } from '/@/components/Drawer';
  import { BasicTree } from '/@/components/Tree/index';
  import DepartDataRuleDrawer from './DepartDataRuleDrawer.vue';
  import { queryRoleTreeList, queryDepartPermission, saveDepartPermission } from '../depart.api';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { translateTitle } from '/@/utils/common/compUtils';
  import { DEPART_MANGE_AUTH_CONFIG_KEY } from '/@/enums/cacheEnum';

  const { prefixCls } = useDesign('j-depart-form-content');
  const { data = {} } = defineProps<{ data: any }>();
  // 当前选中的部门ID，可能会为空，代表未选择部门
  const departId = computed(() => data?.id);

  const basicTree = ref();
  const loading = ref<boolean>(false);
  //树的全部节点信息
  const allTreeKeys = ref([]);
  const treeData = ref<any[]>([]);
  const expandedKeys = ref<Array<any>>([]);
  const selectedKeys = ref<Array<any>>([]);
  const checkedKeys = ref<Array<any>>([]);
  const lastCheckedKeys = ref<Array<any>>([]);
  const checkStrictly = ref(false);

  // 注册数据规则授权弹窗抽屉
  const [registerDataRuleDrawer, dataRuleDrawer] = useDrawer();

  loadData({
    success: () => {
      const localData = localStorage.getItem(DEPART_MANGE_AUTH_CONFIG_KEY);
      if (localData) {
        const { level, expand } = JSON.parse(localData);
        level && toggleRelationAll(level !== 'relation');
        expand && toggleExpandAll(expand === 'openAll');
      }
    },
  });
  watch(departId, () => loadDepartPermission(), { immediate: true });

  async function loadData(options: any = {}) {
    try {
      loading.value = true;
      const { treeList, ids } = await queryRoleTreeList();
      treeData.value = translateTitle(treeList);
      allTreeKeys.value = ids;
      options.success?.(ids);
    } finally {
      loading.value = false;
    }
  }

  async function loadDepartPermission() {
    if (departId.value) {
      try {
        loading.value = true;
        const keys = await queryDepartPermission({ departId: departId.value });
        checkedKeys.value = keys;
        lastCheckedKeys.value = [...keys];
      } finally {
        loading.value = false;
      }
    }
  }

  async function onSubmit() {
    try {
      loading.value = true;
      await saveDepartPermission({
        departId: departId.value,
        permissionIds: checkedKeys.value.join(','),
        lastpermissionIds: lastCheckedKeys.value.join(','),
      });
      await loadData();
      await loadDepartPermission();
    } finally {
      loading.value = false;
    }
  }

  /**
   * 点击选中
   */
  function onCheck(o, e) {
    // checkStrictly: true=>层级独立，false=>层级关联.
    if (checkStrictly.value) {
      checkedKeys.value = o.checked ? o.checked : o;
    } else {
      const keys = getNodeAllKey(e.node, 'children', 'key');
      if (e.checked) {
        checkedKeys.value = [...new Set([...checkedKeys.value, ...keys])];
      } else {
        const result = removeMatchingItems(checkedKeys.value, keys);
        checkedKeys.value = result;
      }
    }
  }
  /**
   * 删除相匹配数组的项
   */
  function removeMatchingItems(arr1, arr2) {
    // 使用哈希表记录 arr2 中的元素
    const hashTable = {};
    for (const item of arr2) {
      hashTable[item] = true;
    }
    // 使用 filter 方法遍历第一个数组，过滤出不在哈希表中存在的项
    return arr1.filter((item: any) => !hashTable[item]);
  }
  /**
   * 获取当前节点及以下所有子孙级的key
   */
  function getNodeAllKey(node: any, children: any, key: string) {
    const result: any = [];
    result.push(node[key]);
    const recursion = (data: any) => {
      data.forEach((item: any) => {
        result.push(item[key]);
        if (item[children]?.length) {
          recursion(item[children]);
        }
      });
    };
    node[children]?.length && recursion(node[children]);
    return result;
  }

  // tree展开事件
  function onExpand($expandedKeys: any) {
    expandedKeys.value = $expandedKeys;
  }

  // tree选中事件
  function onSelect($selectedKeys: any, { selectedNodes }) {
    if (selectedNodes[0]?.ruleFlag) {
      const [functionId] = $selectedKeys;
      dataRuleDrawer.openDrawer(true, { departId, functionId });
    }
    selectedKeys.value = [];
  }

  // 切换展开收起
  async function toggleExpandAll(flag: boolean) {
    if (flag) {
      expandedKeys.value = allTreeKeys.value;
      saveLocalOperation('expand', 'openAll');
    } else {
      expandedKeys.value = [];
      saveLocalOperation('expand', 'closeAll');
    }
  }

  // 切换全选
  async function toggleCheckALL(flag: boolean) {
    checkedKeys.value = flag ? allTreeKeys.value : [];
  }

  // 切换层级关联(独立)
  const toggleRelationAll = (flag: boolean) => {
    checkStrictly.value = flag;
    saveLocalOperation('level', flag ? 'standAlone' : 'relation');
  };
  /**
   * 缓存
   * */
  const saveLocalOperation = (key: string, value: string) => {
    const localData = localStorage.getItem(DEPART_MANGE_AUTH_CONFIG_KEY);
    const obj = localData ? JSON.parse(localData) : {};
    obj[key] = value;
    localStorage.setItem(DEPART_MANGE_AUTH_CONFIG_KEY, JSON.stringify(obj));
  };
</script>

<style lang="less" scoped>
  .depart-rule-tree :deep(.scrollbar__bar) {
    pointer-events: none;
  }
</style>
